import { isArray } from "@/utils/is";
import { Action, Column, Seed } from "../types";

export function cloneSeed(seed: Seed) {
  const ret: Seed = { ...seed };

  const actions = seed.actions
  if(actions) {
      const newActions: Record<string, Action> = {}
      for(const actionName in actions) {
          newActions[actionName] = cloneAction(actions[actionName]);
      }
      ret.actions = newActions;
  }

  const columns = seed.columns
  if(columns) {
      const newColumns: Record<string, Column> = {};
      for(const columnName in columns) {
        newColumns[columnName] = cloneColumn(columns[columnName])
      }
      ret.columns = newColumns;
  }

  if(seed.belongsTo) ret.belongsTo = { ...seed.belongsTo };
  if(seed.hasOne) ret.hasOne = { ...seed.hasOne };
  if(seed.hasMany) ret.hasMany = { ...seed.hasMany };
  if(seed.habtm) ret.habtm = { ...seed.habtm };

  if(seed.declares) ret.declares = seed.declares;
  if(seed.searches) ret.searches = seed.searches;
  if(seed.orders) ret.orders = seed.orders;

  return ret;
}

export function cloneAction(action: Action) {
  const ret: Action = { ...action };

  if(action.declares) ret.declares = isArray(action.declares) ? action.declares : [ action.declares ];
  if(action.searches) ret.searches = isArray(action.searches) ? action.searches : [ action.searches ];
  if(action.orders) ret.orders = isArray(action.orders) ? action.orders : [ action.orders ];
  // if(action.get) ret.get = cloneAction(action.get)
  // if(action.set) ret.set = cloneAction(action.set)

  return ret;
}

function cloneColumn(column: Column) {
  const ret: Column = { ...column }

  if(column.options) ret.options = { ...column.options };

  return ret;
}